<?php
namespace control;
/*
*计时日报类
*/

class timingReportClass extends adIndexClass
{
    private const page = 'timingReport';
    private const table = 'timing_report';
    private const title = '计时日报';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "计时日报编号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'recordDate'  => [
                        'name'  => '日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 300,
                    ],
                    'item'          => [
                        'name'  => '作业项',
                        'width' => 200,
                    ],
                    'staffId'          => [
                        'name'  => '员工',
                        'width' => 200,
                    ],
                    'hour'          => [
                        'name'  => '工时',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "计时日报编号" => text(array("name" => "orderNo")),
                    "生产线"   => selectMultiple(["name" => "lineId", 'table' => "product_line", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'class' => 'width200']),
                    '作业项' => select(["name" => "workItem", 'option' => explode('，', para('workItem'))]),
                ],
                [
                    "日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//名称
        );
        //全等查询数组
        $equal = array(
            "item" => $this->post('workItem'),
            "lineId" => $this->post('lineId'),
            'coid' => self::$coid
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => self::title . "详情", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'staffId':
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(hour),0) as hour",
        ]);
        $total    = [
            'hour'        => self::lostZero($totalQuery['hour'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $this->js() . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }  else {
            $exampleData[] = [];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '日期'=>$example[0],
                            '生产线编号'=>$example[1],
                            '生产线名称'=>$example[2],
                            '班组编号'=>$example[3],
                            '班组名称'=>$example[4],
                            '员工编号'=>$example[5],
                            '员工名称'=>$example[6],
                            '作业项'=>$example[7],
                            '工时'=>$example[8],
                            '备注'=>$example[9],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了车间考勤表导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by recordDate desc,orderNo desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '计时日报编号'=>$array['orderNo'],
                            '日期'=>$array['recordDate'],
                            '生产线'=>productLineClass::getName($array['lineId']),
                            '作业项'=>$array['item'],
                            '员工'=>self::findStaff($array['staffId']),
                            '工时'=>$array['hour'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title.".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }


    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $workItem = para('workItem','，');
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $cell[0] = self::importDateFormat($cell['日期']);
                    $line = query('product_line', " coid = '".self::$coid."' and orderNo = '$cell[生产线编号]'");
                    $team = query('team', " coid = '".self::$coid."' and orderNo = '$cell[班组编号]'");
                    $staff = query('staff',"orderNo = '$cell[员工编号]'");
                    $field = [
                        "id" => self::getId(),
                        'coid'=>self::$coid,
                        'recordDate' => $cell['日期'],
                        'lineId' => $line['id'],
                        'teamId' => $team['id'],
                        'staffId' => $staff['stid'],
                        'item' => $cell['作业项'],
                        'hour' => $cell['工时'],
                        'text' => $cell['备注'],
                    ];
                    $annotation = [
                        'recordDate' => '日期',
                        'lineId' => '生产线',
                        'teamId' => '班组',
                        'staffId' => '员工',
                        'item' => '作业项',
                        'hour' => '工时',
                    ];
                    $rules = [
                        'recordDate' => 'required|date',
                        'lineId' => 'required',
                        'teamId' => 'required',
                        'staffId' => 'required',
                        'item' => 'required',
                        'hour' => 'required|numeric',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();

                    if (empty($job['id']) && !empty($cell[24])) {
                        $text .= "第【{$row_list}】行：职位名称与系统现有职位名称不相符<br>";  // 多个规则提示最前面一条
                    } elseif ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    }elseif(!empty($field['item']) && !in_array($field['item'],$workItem)){
                        $text .= "第【{$row_list}】行：作业项不在可选范围中<br>";
                    }elseif(static::total(array('table'=>'team_detail','where'=>"orderId = '$field[teamId]' and stid = '$field[staffId]' and coid = '".self::$coid."'")) ==0){
                        $text .= "第【{$row_list}】行：未在此班组中找到此员工<br>";
                    }else {
                        $warn = static::insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }




    private function js()
    {
        return <<<eof
<script>
//获取班组员工
function getTeamStaff(e){
       let teamId = e.value;
       $.post(root+'control/adIndex.html?cla=processReport&fun=getTeamStaff',{teamId:teamId},function (res){
             $("#teamStaff").html(res.html)
         },'json');
}
//获取生产线
function getLine(e){
     let val = e.value;
     $.post(root+'control/adIndex.html?cla=machiningOrder&fun=getLine',{val:val},function(res) {
             $("select[name='lineId']").html(res.html);
        },'json');
}
</script>
eof;

    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->post('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $line = query('product_line', "id = '$info[lineId]'");
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "日期：" => text(array('name' => 'recordDate', 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date)),
                must . "生产线：" => repeatSelect(array('name' => 'workshop', 'title' => '生产车间', 'change' => "getLine", 'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用'", 'sqlField' => 'workshop', 'value' => $line['workshop'])) .
                    idSelect(array('name' => 'lineId', 'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用' and workshop = '$line[workshop]'", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '生产线', 'value' => $info['lineId'])),
            ),
            array(
                must . "员工：" => selectMultiple(array("name" => "teamId", 'value' => $info['teamId'], "title" => "班组", "table" => "team", 'change' => 'getTeamStaff', 'where' => " state ='启用' and coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id')) . "<span id='teamStaff' class='width200'>" . selectMultiple(array("name" => "teamStaffId", 'value' => $info['staffId'], "title" => "员工", "table" => "staff", 'where' => "stid in (select stid from team_detail where orderId = '$info[teamId]' and coid = '" . self::$coid . "')", 'sqlField' => 'name', 'sqlId' => 'stid')) . "</span>",
                must . "作业项：" => select(["name" => "item", 'option' => explode('，', para('workItem')), 'title' => '请选择', 'value' => $info['item']]),
            ),
            array(
                must . "工时：" => text(array('name' => 'hour', 'type' => 'number', 'value' => $info['hour'])),
            ),
            array(
                "备注：" => textarea(array('name' => 'text', 'value' => $info['text'], 'class' => 'textarea')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑", 'winFix' => true, "height" => 350, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'recordDate' => $this->post('recordDate'),
            'lineId' => $this->post('lineId'),
            'teamId' => $this->post('teamId'),
            'staffId' => $this->post('teamStaffId'),
            'item' => $this->post('item'),
            'hour' => $this->post('hour'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'recordDate' => '日期',
            'lineId' => '生产线',
            'teamId' => '班组',
            'staffId' => '员工',
            'item' => '作业项',
            'hour' => '工时',
        ];
        $rules = [
            'recordDate' => 'required|date',
            'lineId' => 'required',
            'teamId' => 'required',
            'staffId' => 'required',
            'item' => 'required',
            'hour' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => "staffId = '$field[staffId]' and coid = '" . self::$coid . "' and recordDate = '$field[recordDate]' and item = '$field[item]' and id !='$id'")) > 0) {
            $json['warn'] = "已存在此员工在当前日期的作业项";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'NH' . date('Ymd', strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'coid'=>self::$coid,
                    'orderNo' => $userNo,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $staff = query('staff', "stid = '$field[staffId]'");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】,员工【' . $staff['name'] . '】,日期：' . $field['recordDate'] . '，作业项：' . $field['item'];
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                $staff = query('staff', "stid = '$info[staffId]'");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】，员工【" . $staff['name'] . '】,日期：' . $info['recordDate'] . '，作业项：' . $info['item'] . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'生产线编号',
                    'aliasName'=>'生产线编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'生产线名称',
                    'aliasName'=>'生产线名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'班组编号',
                    'aliasName'=>'班组编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'班组名称',
                    'aliasName'=>'班组名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'员工编号',
                    'aliasName'=>'员工编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'员工名称',
                    'aliasName'=>'员工名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'作业项',
                    'aliasName'=>'作业项',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'工时',
                    'aliasName'=>'工时',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'计时日报编号',
                    'aliasName'=>'计时日报编号',
                ],
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',
                ],
                [
                    'columnName'=>'作业项',
                    'aliasName'=>'作业项',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'工时',
                    'aliasName'=>'工时',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}
